<template>
    <div class="traceability-page">
        <div class="page-header">
            <div class="header-left">
                <h1 class="page-title">溯源管理</h1>
            </div>
        </div>

        <div class="action-bar">
            <div class="action-left">
                <el-button type="primary" @click="Open(null)">
                    <el-icon>
                        <plus />
                    </el-icon>
                    新增
                </el-button>
                <el-button type="danger" @click="deleteSelected">
                    <el-icon>
                        <delete />
                    </el-icon>
                    删除
                </el-button>
            </div>
            <div class="action-right">
                <el-button circle @click="refreshData" title="刷新">
                    <el-icon>
                        <refresh />
                    </el-icon>
                </el-button>
                <el-button circle @click="openSettings" title="设置">
                    <el-icon>
                        <setting />
                    </el-icon>
                </el-button>
                <el-button circle @click="openFilter" title="筛选">
                    <el-icon>
                        <search />
                    </el-icon>
                </el-button>
            </div>
        </div>

        <!-- 搜索栏 -->
        <!-- <div class="search-bar">
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-input v-model="filters.productName" placeholder="商品名称" clearable @input="filterData"
                        size="small" />
                </el-col>
                <el-col :span="4">
                    <el-input v-model="filters.batchNumber" placeholder="生产批次" clearable @input="filterData"
                        size="small" />
                </el-col>
                <el-col :span="4">
                    <el-input v-model="filters.shelfLife" placeholder="保质期(天)" clearable @input="filterData"
                        size="small" />
                </el-col>
                <el-col :span="4">
                    <el-input v-model="filters.licenseNumber" placeholder="生产许可证号" clearable @input="filterData"
                        size="small" />
                </el-col>
                <el-col :span="4">
                    <el-input v-model="filters.enterprise" placeholder="生产企业" clearable @input="filterData"
                        size="small" />
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="filterData" size="small">搜索</el-button>
                    <el-button @click="clearFilters" size="small">重置</el-button>
                </el-col>
            </el-row>
        </div> -->

        <!-- Element Plus 表格 -->
        <div class="table-container">
            <el-table :data="tableData" style="width: 100%" border size="small" max-height="600">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="goodsName" label="商品名称" min-width="120" />
                <el-table-column prop="batch" label="生产批次" min-width="120" />
                <el-table-column prop="shelf_life" label="保质期(天)" min-width="100" />
                <el-table-column prop="productionlicense" label="生产许可证号" min-width="150" />
                <el-table-column prop="production_Enterprise" label="生产企业" min-width="200" />
                <el-table-column prop="information_Completeness" label="信息完善度" min-width="120" />

                <el-table-column prop="createUser" label="创建人" min-width="100" />
                <el-table-column prop="createTime" label="创建时间" min-width="150" />
                <el-table-column prop="updateUser" label="修改人" min-width="100" />
                <el-table-column label="操作" width="280" fixed="right">
                    <template v-slot="scope">
                        <el-button type="primary" size="small"
                            @click="details(scope.row.basic_Traceability, scope.row.batch)">
                            详情
                        </el-button>
                        <el-button type="warning" size="small" @click="Open(scope.row)">
                            修改
                        </el-button>
                        <el-button type="success" size="small" @click="exportCode(scope.row)">
                            导出溯源码
                        </el-button>
                        <el-button type="danger" size="small" @click="Del(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="Page.Index" v-model:page-size="Page.Size"
                :page-sizes="[10, 15, 20, 30, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="Page.totalCount" />
        </div>



    </div>

    <!-- Element Plus 对话框 -->
    <el-dialog v-model="logic.isOpen" title="基本信息" width="700px">
        <el-form label-width="120px">
            <el-form-item label="商品名称" required>
                <el-select v-model="model.gid" placeholder="请选择商品名称" style="width: 100%">
                    <el-option v-for="item in Goods" :label="item.goodsName" :value="item.gid" />
                </el-select>
            </el-form-item>
            <el-form-item label="生产批次" required>
                <el-input v-model="model.batch" placeholder="请输入生产批次" />
            </el-form-item>
            <el-form-item label="保质期(天)" required>
                <el-input-number v-model="model.shelf_life" :min="1" placeholder="请输入保质期天数" style="width: 100%" />
            </el-form-item>
            <el-form-item label="生产许可证号" required>
                <el-input v-model="model.productionlicense" placeholder="请输入生产许可证号" />
            </el-form-item>
            <el-form-item label="生产企业" required>
                <el-input v-model="model.production_Enterprise" placeholder="请输入生产企业" />
            </el-form-item>
            <el-form-item label="封面图" required>
                <el-upload class="avatar-uploader" action="http://localhost:5127/api/Manage/Upload"
                    :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="model.coverImage" :src="model.coverImage" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeModal">取消</el-button>
                <el-button type="primary" @click="save()">
                    保存
                </el-button>
            </span>
        </template>
    </el-dialog>


</template>

<script setup lang="ts">
import { ref, computed, watch, onUnmounted, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'



const router = useRouter()
const route = useRoute()
onMounted(() => {
    show();
    TypeShow();
})

const logic = reactive({
    isOpen: false,

    isAdd: false

})
const show = () => (
    axios({
        url: "http://localhost:5127/api/Manage/Show",
        method: "get",
        params: {
            Index: Page.Index,
            Size: Page.Size,

        }
    })
        .then(res => {
            tableData.value = res.data.data.pageData
            Page.totalCount = res.data.data.totalCount
            Page.totalPage = res.data.data.totalPage
        })
)
const Open = (row: any) => {
    logic.isOpen = true;
    if (row == null) {

        logic.isAdd = true
        model.gid = "",
            model.batch = "",
            model.shelf_life = "",
            model.productionlicense = "",
            model.production_Enterprise = "",
            model.information_Completeness = 0,
            model.productInspectionReportPath = "",
            model.coverImage = ""
    }
    else {

        logic.isAdd = false,
            model.basic_Traceability = row.basic_Traceability,
            model.gid = row.gid,
            model.batch = row.batch,
            model.shelf_life = row.shelf_life,
            model.productionlicense = row.productionlicense,
            model.production_Enterprise = row.production_Enterprise,
            model.information_Completeness = row.information_Completeness,
            model.productInspectionReportPath = row.productInspectionReportPath,
            model.coverImage = row.coverImage


    }
}

const save = () => {
    if (logic.isAdd == true) {
        axios({
            url: 'http://localhost:5127/api/Manage/AddTraceability',
            method: 'post',
            data: model
        })
            .then(res => {
                if (res.data.code == 99300) {
                    ElMessage.success(res.data.message)
                    show();
                    logic.isOpen = false;
                    return;

                }
                else {
                    ElMessage.error(res.data.message)
                    return;
                }
            })
    }
    else {
 axios({
            url: 'http://localhost:5127/api/Manage/UpdTraceability',
            method: 'post',
            data: model
        })
            .then(res => {
                if (res.data.code == 99400) {
                    ElMessage.success(res.data.message)
                    show();
                    logic.isOpen = false;
                    return;

                }
                else {
                    ElMessage.error(res.data.message)
                    return;
                }
            })
    }

}

const Page = reactive({
    Index: 1,
    Size: 10,
    totalCount: 0,
    totalPage: 0
})
watch(Page, () => {
    show();
})
const tableData = ref([

])

const model = reactive({
    basic_Traceability: "",
    gid: "",
    batch: "",
    shelf_life: "",
    productionlicense: "",
    production_Enterprise: "",
    information_Completeness: 100,
    productInspectionReportPath: "aa",
    coverImage: "",

    createUser: "张三",
    isDeleted: false,
})
const Goods = ref<any>([])

const TypeShow = () => {
    axios({
        url: "http://localhost:5127/api/Manage/GoodsShow",
        method: 'get'
    })
        .then(res => {
            Goods.value = res.data.data
        })
}
const Del = (row: any) => {
    console.log(row);
    ElMessageBox.confirm(
        '确定要删除吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {

            axios({
                url: 'http://localhost:5127/api/Manage/DelTraceability',
                method: "post",
                data: row
            })
                .then(res => {
                    if (res.data.code == 99500) {
                        ElMessage.success(res.data.message)
                        show();
                        return;
                    }
                    else {
                        ElMessage.error(res.data.message)
                        return;
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}

///图片
const imageUrl = ref('')

const handleAvatarSuccess = (img: any) => {
    model.coverImage = img;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('文件格式不正确!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件不得大于2mb!')
        return false
    }
    return true
}

const details = (row: any, batch: string) => {
    router.push(
        {
            path: '/Two',
            query: {
                basic_Traceability: row,
                batch: batch
            }
        }
    )
}









const selectedItems = ref<number[]>([])

// 对话框相关状态
const showModal = ref(false)
const formData = ref({
    productName: '',
    batchNumber: '',
    shelfLife: '',
    licenseNumber: '',
    enterprise: '',
    coverImage: null as File | null
})

const currentPage = ref(1)

// 图片预览URL
const coverImagePreviewUrl = computed(() => {
    if (formData.value.coverImage) {
        return URL.createObjectURL(formData.value.coverImage)
    }
    return null
})

// 监听图片URL变化，清理旧的内存
watch(coverImagePreviewUrl, (newUrl, oldUrl) => {
    if (oldUrl) {
        URL.revokeObjectURL(oldUrl)
    }
})

// 组件卸载时清理内存
onUnmounted(() => {
    if (coverImagePreviewUrl.value) {
        URL.revokeObjectURL(coverImagePreviewUrl.value)
    }
})










const goBack = () => {
    router.push('/')
}

const addNewItem = () => {
    showModal.value = true
    resetForm()
}

const closeModal = () => {
    showModal.value = false
    resetForm()
}

const resetForm = () => {
    // 清理图片预览URL
    if (coverImagePreviewUrl.value) {
        URL.revokeObjectURL(coverImagePreviewUrl.value)
    }

    formData.value = {
        productName: '',
        batchNumber: '',
        shelfLife: '',
        licenseNumber: '',
        enterprise: '',
        coverImage: null
    }
}





const deleteSelected = () => {
    console.log('删除选中项目')
}

const refreshData = () => {
    console.log('刷新数据')
}

const openSettings = () => {
    console.log('打开设置')
}

const openFilter = () => {
    console.log('打开筛选')
}


const editItem = (item: any) => {
    console.log('编辑项目', item)
}

const exportCode = (item: any) => {
    console.log('导出溯源码', item)
}


</script>

<style scoped>
.traceability-page {
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: white;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e0e0e0;
}

.page-title {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
}

.close-btn {
    width: 24px;
    height: 24px;
    border: none;
    background: #f5f5f5;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #666;
    transition: all 0.3s;
}

.close-btn:hover {
    background-color: #ff4d4f;
    color: white;
}

.action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #e0e0e0;
}

.search-bar {
    padding: 15px 20px;
    border-bottom: 1px solid #e0e0e0;
    background-color: #fafafa;
}

.action-left {
    display: flex;
    gap: 10px;
}

.action-right {
    display: flex;
    gap: 8px;
}

.table-container {
    flex: 1;
    padding: 20px;
}

.pagination-container {
    display: flex;
    justify-content: center;
    padding: 20px;
    background-color: #fafafa;
}

.image-preview {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    border-radius: 4px;
}
</style>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>